package jehc.djshi.workflow.web;

import cn.hutool.core.collection.CollectionUtil;
import jehc.djshi.common.annotation.NeedLoginUnAuth;
import jehc.djshi.common.base.BaseAction;
import jehc.djshi.common.base.BasePage;
import jehc.djshi.common.base.BaseResult;
import jehc.djshi.common.base.BaseSearch;
import jehc.djshi.common.entity.UserParamInfo;
import jehc.djshi.common.util.StringUtil;
import jehc.djshi.workflow.util.ActivitiUtil;
import jehc.djshi.workflow.vo.LcActivityEntity;
import jehc.djshi.workflow.vo.LcInstanceEntity;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.activiti.engine.history.HistoricActivityInstance;
import org.activiti.engine.history.HistoricActivityInstanceQuery;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.history.HistoricProcessInstanceQuery;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.runtime.ProcessInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 流程实例管理
 * @author 邓纯杰
 *
 */
@Api(value = "流程实例管理",description = "流程实例管理", tags = "流程实例管理")
@RestController
@RequestMapping("/lcInstance")
public class LcInstanceController extends BaseAction {
    @Autowired
    ActivitiUtil activitiUtil;

    /**
     * 查询并分页
     * @param baseSearch
     * @return
     */
    @ApiOperation(value="查询并分页", notes="查询并分页")
    @PostMapping(value="/list")
    @NeedLoginUnAuth
    public BasePage getInstanceList(@RequestBody BaseSearch baseSearch){
        Map<String, Object> condition = baseSearch.convert();
        int start = baseSearch.getStart();
        int pageSize = baseSearch.getPageSize();
        Object deployment_id = condition.get("deployment_id");
        Object instanceType = condition.get("instanceType");

        if(null == deployment_id){
            return new BasePage(0,0,0,null,null,true);
        }
        List<ProcessInstance> processInstances = new ArrayList<>();
        long totalCount =0;
        List<LcInstanceEntity> lcInstanceEntities = new ArrayList<>();


        if(null == instanceType){
            //创建历史流程实例，查询对象
            HistoricProcessInstanceQuery historicProcessInstanceQuery = activitiUtil.getHistoryService().createHistoricProcessInstanceQuery();

            //设置查询条件
            //指定流程定义Id，只查询某个业务流程的实例
            historicProcessInstanceQuery.orderByProcessInstanceId().desc();
            historicProcessInstanceQuery.deploymentId(String.valueOf(deployment_id));
            //设置只查询已完成的
            historicProcessInstanceQuery.finished();
            totalCount = historicProcessInstanceQuery.count();
            historicProcessInstanceQuery.listPage(start, pageSize);
            //数据列表
            List<HistoricProcessInstance> list = historicProcessInstanceQuery.list();
            for (HistoricProcessInstance processInstance : list) {
                LcInstanceEntity lcInstanceEntity = new LcInstanceEntity();
                lcInstanceEntity.setId(processInstance.getId());
                lcInstanceEntity.setBusinessKey(processInstance.getBusinessKey());
                lcInstanceEntity.setDeploymentId(processInstance.getDeploymentId());
                lcInstanceEntity.setDescription(processInstance.getDescription());
                lcInstanceEntity.setTaskName("-");
                lcInstanceEntity.setName(processInstance.getName());
                lcInstanceEntity.setSuperExecutionId(processInstance.getSuperProcessInstanceId());
                lcInstanceEntity.setProcessDefinitionId(processInstance.getProcessDefinitionId());
                lcInstanceEntity.setProcessDefinitionName(processInstance.getProcessDefinitionName());
                lcInstanceEntity.setProcessInstanceId(processInstance.getId());
                lcInstanceEntity.setStartTime(processInstance.getStartTime());
                lcInstanceEntity.setEndTime(processInstance.getEndTime());
                lcInstanceEntity.setEnd(true);
                lcInstanceEntity.setDurationInMillis(processInstance.getDurationInMillis());
                lcInstanceEntities.add(lcInstanceEntity);
            }
        }else{
            //运行中实例
            processInstances = activitiUtil.getRuntimeService().createProcessInstanceQuery().deploymentId(String.valueOf(deployment_id)).orderByProcessInstanceId().desc().listPage(start, pageSize);
            totalCount = (int)activitiUtil.getRuntimeService().createProcessInstanceQuery().deploymentId(String.valueOf(deployment_id)).count();
            for(ProcessInstance processInstance: processInstances){
                LcInstanceEntity lcInstanceEntity = new LcInstanceEntity();
                lcInstanceEntity.setId(processInstance.getId());
                lcInstanceEntity.setBusinessKey(processInstance.getBusinessKey());
                lcInstanceEntity.setDeploymentId(processInstance.getDeploymentId());
                lcInstanceEntity.setDescription(processInstance.getDescription());
                lcInstanceEntity.setName(processInstance.getName());
                lcInstanceEntity.setSuperExecutionId(processInstance.getSuperExecutionId());
                lcInstanceEntity.setSuspended(processInstance.isSuspended());
                lcInstanceEntity.setProcessDefinitionId(processInstance.getProcessDefinitionId());
                lcInstanceEntity.setProcessDefinitionName(processInstance.getProcessDefinitionName());
                lcInstanceEntity.setActivityId(processInstance.getActivityId());
                lcInstanceEntity.setProcessInstanceId(processInstance.getProcessInstanceId());
                HistoricProcessInstance historicProcessInstance = activitiUtil.getHistoryProcessInstance(processInstance.getProcessInstanceId());
                lcInstanceEntity.setEnd(false);
                if(null != historicProcessInstance){
                    lcInstanceEntity.setStartTime(historicProcessInstance.getStartTime());
                    lcInstanceEntity.setEndTime(historicProcessInstance.getEndTime());
                    lcInstanceEntity.setDurationInMillis(historicProcessInstance.getDurationInMillis());
                }
                lcInstanceEntities.add(lcInstanceEntity);
            }
        }
        return new BasePage(start,pageSize,pageSize,totalCount,lcInstanceEntities,true);
    }


    /**
     * 挂起流程实例
     * @param instanceId
     * @return
     */
    @ApiOperation(value="挂起流程实例", notes="挂起流程实例")
    @GetMapping(value="/suspend/{instanceId}")
    public BaseResult suspend(@PathVariable("instanceId")String instanceId){
        return outAudStr(activitiUtil.suspendProcessInstanceById(instanceId));
    }

    /**
     * 激活流程实例
     * @param instanceId
     * @return
     */
    @ApiOperation(value="激活流程实例", notes="激活流程实例")
    @GetMapping(value="/activate/{instanceId}")
    public BaseResult activate(@PathVariable("instanceId")String instanceId){
        return outAudStr(activitiUtil.activateProcessInstanceById(instanceId));
    }


    /**
     * 查询流程实例全部节点并分页
     * @param baseSearch
     * @return
     */
    @ApiOperation(value="查询流程实例全部节点并分页", notes="查询流程实例全部节点并分页")
    @PostMapping(value="/list/activity")
    @NeedLoginUnAuth
    public BasePage getInstanceActivityList(@RequestBody BaseSearch baseSearch){
        Map<String, Object> condition = baseSearch.convert();
        int start = baseSearch.getStart();
        int pageSize = baseSearch.getPageSize();
        Object instanceId = condition.get("instanceId");

        Object finished = condition.get("finished");

        if(null == instanceId){
            return new BasePage(0,0,0,null,null,true);
        }
        long totalCount =0;
        HistoricActivityInstanceQuery historicActivityInstanceQuery=activitiUtil.getHistoryService()
                    .createHistoricActivityInstanceQuery(); // 创建历史活动实例查询
        //设置查询条件
        //指定流程定义Id，只查询某个业务流程的实例
        historicActivityInstanceQuery.orderByProcessInstanceId().desc();
        historicActivityInstanceQuery.processInstanceId(String.valueOf(instanceId));
        if(null != finished){
            //设置只查询已完成的
            historicActivityInstanceQuery.finished();
        }
        totalCount = historicActivityInstanceQuery.count();
        List<HistoricActivityInstance> historicActivityInstances = historicActivityInstanceQuery.listPage(start, pageSize);

        List<LcActivityEntity> lcActivityEntities = new ArrayList<>();
        for(HistoricActivityInstance historicActivityInstance :historicActivityInstances){
            LcActivityEntity lcActivityEntity = new LcActivityEntity();
            lcActivityEntity.setId(historicActivityInstance.getId());//活动ID
            lcActivityEntity.setProcessInstanceId(historicActivityInstance.getProcessInstanceId());//流程实例ID
            lcActivityEntity.setActivityName(historicActivityInstance.getActivityName());//活动名称
            lcActivityEntity.setActivityType(historicActivityInstance.getActivityType());

            if(!StringUtil.isEmpty(historicActivityInstance.getAssignee())){//办理人
                UserParamInfo userParamInfo = new UserParamInfo(historicActivityInstance.getAssignee());
                userParamInfo = infoList(userParamInfo);
                if(CollectionUtil.isNotEmpty(userParamInfo.getUserinfoEntities())){
                    lcActivityEntity.setAssignee(userParamInfo.getUserinfoEntities().get(0).getXt_userinfo_realName());
                }
            }else{
                lcActivityEntity.setAssignee("X");
            }
            lcActivityEntity.setDurationInMillis(historicActivityInstance.getDurationInMillis());
            lcActivityEntity.setStartTime(historicActivityInstance.getStartTime());
            lcActivityEntity.setEndTime(historicActivityInstance.getEndTime());
            lcActivityEntities.add(lcActivityEntity);
        }
        return new BasePage(start,pageSize,pageSize,totalCount,lcActivityEntities,true);
    }

    /**
     * 查询部署详情
     * @param deploymentId
     * @return
     */
    @ApiOperation(value="查询部署详情", notes="查询部署详情")
    @GetMapping(value="/deployment/get/{deploymentId}")
    public BaseResult getDeploymentById(@PathVariable("deploymentId")String deploymentId){
        Deployment deployment = activitiUtil.getDeploymentById(deploymentId);
        return outDataStr(deployment);
    }
}
